package com.cms.biz.dict.impl;

import java.sql.ResultSet;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cms.biz.dict.CMSContractServiceMgr;
import com.common.util.EMPSQLUtil;
import com.efounder.builder.base.data.DataSetUtils;
import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.builder.meta.domodel.SYS_OBJCOLS;
import com.efounder.dctbuilder.rule.EMPCodeRuler;
import com.efounder.eai.data.JParamObject;
import com.efounder.eai.data.JResponseObject;
import com.efounder.form.server.resolver.util.BizFormUtil;
import com.efounder.sql.JConnection;
import com.efounder.sql.JStatement;
import com.framework.sys.business.AbstractBusinessObjectServiceMgr;
import com.metadata.biz.MetaDataServiceMgr;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import com.pub.util.StringFunction;

@Transactional(rollbackFor = Exception.class)
@Service("CMSContractServiceMgr")
public class CMSContractMgrImpl extends AbstractBusinessObjectServiceMgr implements CMSContractServiceMgr {
	
	@Autowired
	private         JdbcTemplate            jdbcTemplate;
	
	@Autowired
	private   MetaDataServiceMgr           dictMeataData;
	
	public EFDataSet getHTZDMXDataSetRow(String F_FLBH, String F_HTBH) {
		JConnection      conn = null;
		JStatement       stmt = null;
		ResultSet          rs = null;
		String         strSql = "";
		EFDataSet     dataset = EFDataSet.getInstance("HTZDMX");
		
		try {
			conn = JConnection.getInstance(jdbcTemplate.getDataSource().getConnection());
			stmt = conn.createStatement();

			strSql = "select HTZDMX.F_FLBH as F_FLBH, HTZDMX.F_HTBH as F_HTBH, HTZDMX.F_WZBM, "
				   + " HTZDMX.F_CPMC as F_CPMC, HTZDMX.F_GGXH as F_GGXH, round(HTZDMX.F_DJ, 2) AS F_DJ, round(HTZDMX.F_SL, 2) AS F_SL, round(HTZDMX.F_DJ*HTZDMX.F_SL, 2) AS F_JE"
				   + " from HTZDMX"
				   + " where 1 = 1 ";
			if(F_HTBH != null && F_HTBH.trim().length() > 0) {
				strSql += " and HTZDMX.F_HTBH = '" + F_HTBH + "'";
			}
			if(F_FLBH != null && F_FLBH.trim().length() > 0) {
				strSql += " and HTZDMX.F_FLBH = '" + F_FLBH + "'";
			}
			strSql += " order by F_FLBH";
			rs = stmt.executeQuery(strSql);
			dataset = DataSetUtils.resultSet2DataSet(rs, dataset);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				EMPSQLUtil.closeAllResources(rs, stmt, conn);	
			} catch(Exception ce) {
				ce.printStackTrace();
			}
		}
		return dataset;
	}

	public JResponseObject insertHTXM(JParamObject PO, EFRowSet rowset) {
		JConnection               conn = null;
		JStatement                stmt = null;
		ResultSet                   rs = null;
		String                  strSql = "";
		String             PARENT_XMBH = PO.GetValueByParamName("PARENT_XMBH", "");
		int                       F_JS = 0;
		int                 struLength = 0;
		int                     iMaxBM = 0;
		String                    stub = "";
		String              DCT_BMSTRU = "";
		String                 maxXMBH = "";
		String              newMaxXMBH = "";
		String                 newXMBH = "";
		String                   maxBM = "0";
		String                errorMsg = "";
		String              strPreCode = "";
		String                codeRule = "";
		EFRowSet           bizMetaData = null;
		JResponseObject             RO = new JResponseObject();
		
		try {
			conn = JConnection.getInstance(jdbcTemplate.getDataSource().getConnection());
			stmt = conn.createStatement();

			//获取父节点编号级数
			strSql = " select * from HTXMZD where F_XMBH = '" + PARENT_XMBH + "'";
			rs = stmt.executeQuery(strSql);
			if(rs != null && rs.next()) F_JS = rs.getInt("F_JS");
			
			//获取编码规则
			strSql = " select * from SYS_DICTS where DCT_ID = 'HTXMZD'";
			rs = stmt.executeQuery(strSql);
			if(rs != null && rs.next()) DCT_BMSTRU = rs.getString("DCT_BMSTRU");
			
			//获取编码方式
			strSql = " select * from SYS_DCT_CST where DCT_ID = 'HTXMZD' and DCT_KEY = 'CodeRule'";
			rs = stmt.executeQuery(strSql);
			if(rs != null && rs.next()) codeRule = rs.getString("DCT_VAL");
			
			//获取最大编号
			strSql = " select max(F_XMBH) as F_XMBH from HTXMZD where F_XMBH like '" + PARENT_XMBH + "%' and F_JS = " + (F_JS + 1);
			rs = stmt.executeQuery(strSql);
			
			if(rs != null && rs.next()) {
				maxXMBH = rs.getString("F_XMBH");
				if(maxXMBH !=  null) {
					//如果添加1级编号，获取流水号+1
					if(F_JS == 0) {
						struLength = 0;
						EMPCodeRuler codeRuler = new EMPCodeRuler();
						strPreCode = codeRuler.getPrefixByRule(PO, codeRule, null);
						maxBM = maxXMBH.substring(strPreCode.length());
					} 
					//根据编码规则获取当前级数的最大编码
					else {
						struLength = StringFunction.GetStructLength(DCT_BMSTRU, F_JS);
						maxBM = maxXMBH.substring(struLength);
					}
				} else {
					maxXMBH = PARENT_XMBH;
					struLength = PARENT_XMBH.length();
					//如果添加1级编号，获取流水号+1
					if(F_JS == 0) {
						EMPCodeRuler codeRuler = new EMPCodeRuler();
						strPreCode = codeRuler.getPrefixByRule(PO, codeRule, null);
					} 
				}
				try {
					iMaxBM = Integer.parseInt(maxBM);
				} catch(Exception ce) {
					iMaxBM = 0;
				}
			}
			iMaxBM++;
			stub = DCT_BMSTRU.substring(F_JS, F_JS + 1);
			newMaxXMBH = StringFunction.FillZeroFromBegin(iMaxBM, Integer.parseInt(stub,36) - strPreCode.length());
			newXMBH = strPreCode + maxXMBH.substring(0, struLength) + newMaxXMBH;
			
//			strSql = " insert into HTXMZD (F_XMBH,F_XMMC,F_JS,F_MX,F_SYZT) values('" + newXMBH 
//			       + "','" + rowset.getString("F_XMMC", "") + "'," + rowset.getNumber("F_JS", 0).intValue()
//			       + ",'" + rowset.getString("F_MX", "") + "','" + rowset.getString("F_SYZT", "") + "')";			
//			stmt.execute(strSql);
			
			rowset.put("F_XMBH", newXMBH);
			
			bizMetaData = BizFormUtil.getBIZMetaData(stmt, "HTXMZD");
			BizFormUtil.saveRowSetData(stmt, "HTXMZD", rowset, bizMetaData.getDataSet(SYS_OBJCOLS._SYS_OBJCOLS_));
			conn.commit();
			
			RO.setErrorCode(1);
			RO.setResponseObject("数据添加成功！");
			conn.commit();
			return RO;
		} catch (Exception ce) {			
			RO.setErrorCode(-1);
			if(ce.getCause()!= null) {
				if(ce.getCause().getMessage() == null) {
					Throwable ourCause = ce.getCause();
		            if (ourCause != null) {
		            	StackTraceElement[] trace = ourCause.getStackTrace();
		                int m = trace.length-1, n = trace.length-1;

		                errorMsg = "Caused by: " + this;
		                for (int i=0; i <= m; i++)
		                	errorMsg += "\tat " + trace[i];
		            }
		            RO.setErrorString(errorMsg);
		            ce.printStackTrace();
				} else {
					RO.setErrorString(ce.getCause().getMessage());
				} 
			} else {
				MySQLIntegrityConstraintViolationException ee = (MySQLIntegrityConstraintViolationException) ce;
				RO.setErrorString(ee.getMessage());
			}
			
			RO.setResponseObject("数据添加成功！");
		} finally {
			try {
				EMPSQLUtil.closeAllResources(rs, stmt, conn);	
			} catch(Exception ce) {
				ce.printStackTrace();
			}
		}
		return RO;
	}
	
	public void getInsertSql() {
		
	}
}
